import sqlite3 from 'sqlite3';
import { getHash } from '../utils';

const db = new sqlite3.Database("db.db");

/*
* ***********************************************************************************************
* Token
* *********************************************************************************************** 
*/

// 获取token
export const getToken = (token) => {
	return new Promise((resolve, reject) => {
		db.get("select * from accessToken where token = ?", token , (err, row) => {
			if(err){
				reject(err);
			} else {
				resolve(row);
			}
		});
	})
}

// 删除token
export const removeToken = (userId) => {
	return new Promise((resolve, reject) => {
		db.run("delete from accessToken where userId = ?", userId, (err) => {
			if(err){
				reject(err);
			} else {
				resolve(true);
			}
		})
	})
}

// 新建token
export const createToken = ({token,userId}) => {
	return new Promise((resolve, reject) => {
		const ctime = Date.now();
		db.run("insert into accessToken (token, userId, ctime) values (?,?,?)",[ token,userId,ctime ], (err) => {
			if(err){
				reject(err);
			} else {
				resolve({token,userId,ctime});
			}
		})
	})
}


/*
* ***********************************************************************************************
* user
* *********************************************************************************************** 
*/

// 通过账户获取用户
export const getUserByUsername = (username) => {
	return new Promise((resolve, reject) => {
		db.get("select * from user where username = ?", username , (err, row) => {
			if(err){
				reject(err);
			} else {
				resolve(row);
			}
		})
	})
}

// 通过用户名和密码获取用户
export const getUserByUserAndPass = ({username, password}) => {
	return new Promise((resolve, reject) => {
		db.get("select * from user where username = ? and password = ? ",[username, password],(err, row)=>{
			if(err){
				reject(err);
			} else {
				resolve(row);
			}
		})
	})
}

// 通过ID获取用户
export const getUserById = (userId) => {
	return new Promise((resolve, reject) => {
		db.get("select * from user where userId = ? ", userId, (err, row)=>{
			if(err){
				reject(err);
			} else {
				resolve(row);
			}
		})
	})
}

// 创建用户
export const createUser = ({username, password}) => {
	return new Promise((resolve, reject) =>{
		const userId = getHash(new Date().getTime().toString());
		const ctime = Date.now();
		db.run("insert into user (userId, username, password, ctime) values (?,?,?,?)", [userId, username, password, ctime], (err) => {
			if(err){
				reject(err);
			} else {
				resolve({userId, username, password, ctime});
			}
		});
	}) 
}

